package fr.esiea.erg5203.persistence.database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import fr.esiea.erg5203.business.Contact;

public final class ApplicationLifeCycleDatabase {

	private static volatile ApplicationLifeCycleDatabase instance = null;
	private static Map<Integer, Contact> database = null;
	private static int idCounter = 0;
	
	private ApplicationLifeCycleDatabase(){		
		super();
		
		database = new HashMap<Integer, Contact>();
	}
	
	public final static ApplicationLifeCycleDatabase getInstance()
	{
		if(ApplicationLifeCycleDatabase.instance == null)
		{
			synchronized (ApplicationLifeCycleDatabase.class)
			{
				if(ApplicationLifeCycleDatabase.instance == null) ApplicationLifeCycleDatabase.instance = new ApplicationLifeCycleDatabase();
			}
		}		
		return instance;		
	}
	
	public List<Contact> getAll()
	{		
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		Iterator<Contact> it = database.values().iterator();
		
		while(it.hasNext())
		{
			contacts.add((Contact) it.next());
		}	
		
		return contacts;
	}
	
	public Contact find(int id)
	{						
		return database.get(Integer.valueOf(id));
	}
	
	public void add(Contact contact)
	{
		
		contact.setId(idCounter);			
		database.put(Integer.valueOf(contact.getId()), contact);
		
		idCounter++;
	}
	
	public void update(Contact contact)
	{
		database.put(Integer.valueOf(contact.getId()), contact);
	}
	
	public void remove(int id)
	{
		database.remove(id);
	}
}
